import { EllipsisOutlined, SearchOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown, PageContainer } from '@ant-design/pro-components';
import { Button, Dropdown, Input, message, Modal, Form, Select, Space, DatePicker, Popconfirm } from 'antd';
import { GetActivity, PatchActivity, DeleteActivity, PostActivity } from '@/api/home'
import { useState, useEffect ,useRef} from 'react'
import { flushSync } from 'react-dom';
import { useModel } from 'umi';
import moment from 'moment';
const { Option } = Select;
const { RangePicker } = DatePicker;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};


export default () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 初始化选中的行 keys  
  const actionRef = useRef(); //绑定Ref 触发刷新
  const [total, setTotal] = useState(0); // 记录数据总条数
  const [isModalOpen, setIsModalOpen] = useState(false); // 添加数据-弹出层设置
  const [loading, setLoading] = useState(true); // 加载数据时候的loading
  const [isModalOpen02, setIsModalOpen02] = useState(false); // 弹出层2 回答审批意见时候进行
  const [form] = Form.useForm(); // 添加数据的表单
  const [tableListDataSource, setTableListDataSource] = useState([]) //存储表单的数据源
  const [inputValue, setInputValue] = useState('')
  // const permission = useModel('demo')
  const { initialState, setInitialState } = useModel('@@initialState'); // 获取State持久化数据
  const permissions = initialState.currentUser.permissionslist
  const [options01, setOptions01] = useState([])
  const [offer,setOffer] = useState('') 
  const userId = initialState.currentUser.userinfo.id
  // delete

  const onGenderChange = (value: string) => {
    switch (value) {
      case 'male':
        form.setFieldsValue({ note: 'Hi, man!' });
        break;
      case 'female':
        form.setFieldsValue({ note: 'Hi, lady!' });
        break;
      case 'other':
        form.setFieldsValue({ note: 'Hi there!' });
        break;
      default:
    }
  };
  // 清空表单信息
  const onReset = () => {
    form.resetFields();
  };
  // const onFill = () => {
  //   form.setFieldsValue({ note: 'Hello world!', gender: 'male' });
  // };
  const showModal = () => {
    setIsModalOpen(true);
    // console.log("tableListDataSourcetableListDataSource", tableListDataSource)
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 添加数据
  const AddData = async (options) => {
    try {
      delete options.id
      options.user_id = userId
      // console.log("options", options)
      // options.
      const data = await PostActivity(options)
      // 将data数据展平 
      // 将data数据展平 
      const flattenedDataSource = { ...data, username: data.user ? data.user.username : null }
      setTableListDataSource([...tableListDataSource, flattenedDataSource])
      // console.log("2",)
      message.success("添加成功")
      actionRef.current.reload(); 
      setIsModalOpen(false)
    } catch (err) {
      console.log(err)
    }
  }
  // 修改 Onsave
  const PatchData = async (uid, options,del='d') => {
    
    try {
      // console.log("--options",options)
      const { status, activity_name, activity_description, start_date, end_date, venue, participant_count, idea } = options
      //  console.log({status})
      const data = await PatchActivity(uid, { status, activity_name, activity_description, start_date, end_date, venue, participant_count, idea ,update_name:initialState.currentUser?.userinfo.username})
      //  GetData() //暂时利用get 获取数据

      // 将data数据展平 
      const flattenedDataSource = tableListDataSource.map(item => {
        // console.log(item.id,"----",uid)
        if (item.id === uid) {
          return { ...data, username: item.user ? item.user.username : null }
        }
        return item
      });
      console.log(data)
      console.log('del',del)
      if(del === 'del'){
        actionRef.current.reload();
      }
      // flushSync(setLogo(true))
      setTableListDataSource(flattenedDataSource)
      message.success("修改成功！")
    } catch (err) {
      console.log(err)
      message.error("修改失败！")
      // flushSync(setLogo(false))
      // setLogo(false)
    }
    // console.log('保存了')
  }
  // 获取表格数据
  const GetData = async (options) => {
    try {
      // console.log(status)
      // console.log(options[0])
      // const data = await GetActivity(page, pagesize,!status? '':status,!activityname? '':activityname,!id? '': id)
      const data = await GetActivity(options.page, options.pagesize,options.status,options.activityname,options.id,!options.options[0] ? '':options.options[0],!options.options[1] ? '':options.options[1])
      flushSync(setTotal(data.count))
      // console.log('count',total)
      // 将data数据展平 
      const flattenedDataSource = data.results.map(item => ({
        ...item,
        username: item.user ? item.user.username : null, // 将username提升到顶级  
        // ... 其他需要提升的字段  
      }));
      // tableListDataSource = flattenedDataSource
      flushSync(setTableListDataSource(flattenedDataSource))
      // console.log("tableListDataSourcetableListDataSource", tableListDataSource)
      // console.log(data)
      setTimeout(() => {
        // setData([{ key: '1', name: 'John Doe', age: 30 }]);
        setLoading(false);
      }, 100);
    } catch (err) {
      message.info("数据初始化失败~")
      setTimeout(() => {
        // setData([{ key: '1', name: 'John Doe', age: 30 }]);
        setLoading(false);
      }, 100);
    }
  }
  const DeleteData = async (id) =>{
    try {
      await DeleteActivity(id)
      // console.log('删除返回的数据：',data)
      setTableListDataSource(tableListDataSource.filter((item) => item.id !== id));
      message.success("删除成功")
    } catch(err) {
      message.error("删除失败~")
    }
  }
  const onFinish = (values: any) => {
    // console.log("表单提交信息：", values);

    const { activitycount, activitydescribe, activityposstion, activitystatus, activityname } = values
    const [startDateStr, endDateStr] = values.activitydate
    const startDate = moment(startDateStr).format('YYYY-MM-DD');
    const endDate = moment(endDateStr).format('YYYY-MM-DD');
    AddData({
      "activity_name": activityname,
      "activity_description": activitydescribe,
      "start_date": startDate,
      "end_date": endDate,
      "venue": activityposstion,
      "participant_count": activitycount,
      "status": activitystatus
    })
    // console.log('Start Date:', startDate);  
    // console.log('End Date:', endDate); 
    // message.success('信息创建成功~');
  };
  // 组件初始化 时候运行
  useEffect(() => {
    // GetData(1,20);
    // console.log(initialState.currentUser,initialState.currentUser.permissionslist.includes('submit_activity'))
  }, []); // 空数组作为第二个参数，表示只在组件加载时运行一次
  
  const rowSelection = {  
    selectedRowKeys,  
    onChange: (newSelectedRowKeys, newSelectedRows) => {  
      setSelectedRowKeys(newSelectedRowKeys);  
      console.log('newSelectedRowKeys',newSelectedRowKeys)
      // 在这里可以处理选中行数据 newSelectedRows
    },  
    preserveSelectedRowKeys: true, // 翻页时保留选中状态  
  };  
  const columns = [
    {
      title: '序号',
      width: 48,
      dataIndex: 'index',
      editable: false,// 编辑禁用
      search: false,
      render: (text, record, index) => <span>{index + 1}</span>,
      valueType: 'index',
    },
    {
      title: '编号',
      dataIndex: 'id',
      editable: false,// 编辑禁用
      // valueType: 'indexBorder',
      width: 55,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      editable: false,
      ellipsis: true,
      search: false,
    },
    {
      title: '创建者',
      dataIndex: 'username',
      // width: 66,
      editable: false,
      search: false,
    },
    {
      title: '活动名称',
      ellipsis: true,
      dataIndex: 'activity_name',
      // search: false
    },
    {
      title: '描述',
      dataIndex: 'activity_description',
      search: false,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '开始时间',
      dataIndex: 'start_date',
      valueType: 'date',
      search: false,
    },
    {
      title: '结束时间',
      dataIndex: 'end_date',
      valueType: 'date',
      search: false,
    },
    {
      title: '人数',
      dataIndex: 'participant_count',
      search: false,
      width: 88,
      // ellipsis: true, 后来也遇见了好多人，
      // copyable: true,
    },
    {
      title: '审批建议',
      dataIndex: 'idea',
      editable: false,
      search: false,
      // width: 48,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      editable: false,
      // initialValue: 'all',
      filters: true,
      onFilter: true,
      valueEnum: {
        '0': { text: '待提交', status: 'Default' },
        '1': { text: '已提交', status: 'Processing' },
        '2': { text: '已同意', status: 'Success' },
        '3': { text: '已拒绝', status: 'Error' },
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updated_at',
      valueType: 'dateTime',
      ellipsis: true,
      editable: false,
      search: false,
    },
    {
      title: '修改人',
      dataIndex: 'update_name',
      // valueType: 'dateTime',
      editable: false,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      // width: 200,
      render: (text, record, _, action) => {
        if (record['status'] === '0' && permissions.includes('submit_activity')) {
          return [
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record['id']);
              }}
            >
              修改
            </a>,
            <Popconfirm
              key="commit"
              title="确定要提交这条记录吗？"
              onConfirm={() => {
                PatchData(record.id, { status: "1" })
              }}
              onCancel={() => {
                message.info('取消提交');
              }}
              okText="确认"
              cancelText="取消"
            >
              <a>提交</a>
            </Popconfirm>,
          ]
        } else if (record['status'] === '1' && permissions.includes('submit_activity')) {
          return [<a key="monitor" style={{ color: 'rgba(0,0,0,.25)', cursor: 'not-allowed', }}>修改</a>,
          // <a
          //   key="editable"
          //   onClick={() => {
          //     PatchData(record.id, { status: "0", idea: '' })
          //   }}
          // >
          //   撤回
          // </a>,
           <Popconfirm
           key="commit"
           title="确定要撤回这条记录吗？"
           onConfirm={() => {
             PatchData(record.id, { status: "0" })
            //  setTimeout(()=>{actionRef.current.reload(); },200)
           }}
           onCancel={() => {
             message.info('取消撤回');
           }}
           okText="确认"
           cancelText="取消"
         >
           <a>撤回</a>
         </Popconfirm>,]
        } else if (permissions.includes('submit_activity')) {
          return [<a key="monitor" style={{ color: 'rgba(0,0,0,.25)', cursor: 'not-allowed', }}>审批结束</a>]
        }
          else if (permissions.includes('recall_activity')){
          return [<Popconfirm
            key="commit"
            title="确定要撤回这条记录吗？"
            onConfirm={() => {
              PatchData(record.id, { status: "1" },'del')
            }}
            onCancel={() => {
              message.info('取消撤回');
            }}
            okText="确认"
            cancelText="取消"
          >
            <a>撤回</a>
          </Popconfirm>]
        }
          else if(record['status'] === '2' || record['status'] === '3'){
          return [<a key="monitor" style={{ color: 'rgba(0,0,0,.25)', cursor: 'not-allowed', }}>完成审批</a>,
          // <a key="monitor" style={{ color: 'rgba(0,0,0,.25)', cursor: 'not-allowed', }}>拒绝</a>
        ]
        } else if(record['status'] === '1'){
          return [
            <>
              <a
                key="editable"
                onClick={() => {
                  setIsModalOpen02(true)
                  setOptions01({ id: record.id, status: "2" })
                  setOffer('请您填写同意审批的建议~')
                  // console.log(record.id)

                }}
              >
                {/* <Modal title="同意审批意见~" open={isModalOpen02} onOk={() => {
                setIsModalOpen02(false); 
                console.log('inputValue',record.id,inputValue)
                // PatchData(record.id, { status: "2", idea: inputValue })
              }}
                onCancel={() => { setIsModalOpen02(false) }}>
                <Input
                  placeholder="请填写审批意见~"
                  value={inputValue} // 设置Input的值为当前的状态值  
                  onChange={(e) => { setInputValue(e.target.value) }} // 当Input的值改变时调用这个函数  
                />
              </Modal> */}
                同意
              </a>
            </>
            ,
            <>
              {/* <Modal title="拒绝审批意见~" open={isModalOpen02} onOk={() => {
                setIsModalOpen02(false); 
                // PatchData(record.id, { status: "3", idea: inputValue })
              }}
                onCancel={() => { setIsModalOpen02(false) }}>
                <Input
                  placeholder="请填写审批意见~"
                  value={inputValue} // 设置Input的值为当前的状态值  
                  onChange={(e) => { setInputValue(e.target.value) }} // 当Input的值改变时调用这个函数  
                />
              </Modal> */}
              <a
                key="editable"
                onClick={() => {
                  setIsModalOpen02(true)
                  setOptions01({ id: record.id, status: "3" })
                  setOffer('请您填写拒绝的审批建议~')
                  // action?.startEditable?.(record['id']);
                }}
              >
                拒绝
              </a>
            </>
            // <Popconfirm
            //   key="commit"
            //   title="确认同意？"
            //   onConfirm={() => {
            //     setIsModalOpen02(true)
            //     console.log('inputValue:',inputValue)
            //     PatchData(record.id, { status: "2" })
            //   }}
            //   okText="确认"

            //   cancelText="取消"
            // >
            //   <a>同意</a>
            // </Popconfirm>,
            // <Popconfirm
            //   key="commit"
            //   title="确认拒绝？"
            //   onConfirm={() => {
            //     PatchData(record.id, { status: "3" })
            //   }}
            //   okText="确认"
            //   cancelText="取消"
            // >
            //   <a>拒绝</a>
            // </Popconfirm>
          ]
        }
      },
    },
    {
      title: '创建时间',
      dataIndex: 'start_endDateTimeRange',
      valueType: 'dateTimeRange',
      render: () => null, 
      width:0,
      hideInTable:true //控制table显示
      // search: false,
      // filters: false, // 禁用默认的筛选
    },
    // {
    //   title: '结束时间',
    //   dataIndex: 'end_date',
    //   valueType: 'date',
    //   search: false,
    // },
  ];
  return (
    <PageContainer>
      <Modal title={offer}
        open={isModalOpen02}
        onOk={() => {
          setIsModalOpen02(false);
          PatchData(options01.id, { ...options01, idea: inputValue })
          setInputValue('')
        }}
        onCancel={() => { setIsModalOpen02(false) }}>
        <Input.TextArea
          placeholder="请您填写同意 or 拒绝的审批建议~"
          value={inputValue} // 设置Input的值为当前的状态值  
          onChange={(e) => { setInputValue(e.target.value) }} // 当Input的值改变时调用这个函数  
        />
      </Modal>

      <ProTable
        rowSelection={rowSelection}
        actionRef={actionRef}
        loading={loading}
        columns={columns}
        // 适合进行数据请求
        request={(params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          setLoading(true)
          // console.log(params, sorter, filter);
          GetData({
            page:params.current, 
            pagesize:params.pageSize,
            status:params.status,
            activityname:params.activity_name,
            id:params.id,
            options:!params.start_endDateTimeRange? {}:params.start_endDateTimeRange
          })
          return {
            data: tableListDataSource,
            success: true,
          };
        }}
        dataSource={tableListDataSource} // 源数据设置
        rowKey="id"
        // 分页设置
        pagination={{
          total: total, // 设置总数据条数
          defaultPageSize: 10, // 设置默认的每页条数为20
          onChange: (page, pageSize) => {
            // console.log('Current Page:', page);
            // console.log('Page Size:', pageSize);
            // 在这里可以执行相应的操作，比如发送请求获取对应页的数据
          },
          showSizeChanger: true, // 显示可调整每页条数功能
          pageSizeOptions: ['10', '20', '30'], // 指定每页可以显示多少条
          showQuickJumper: true, // 显示快速跳转到某页功能
        }}
        search={{
          layout: 'vertical',
          defaultCollapsed: true,
          // labelWidth:10,
          labelWidth: 'auto',
          // span: 5, // 设置栅格个数
          showHiddenNum: true,
        //   optionRender:()=>[<Button key="danger" danger onClick={() => { message.error("功能暂未开通~") }}>
        //   批量导出
        // </Button>,]
          // optionRender:false
        }}
        
        editable={{
          type: 'single',
          // editableKeys: editableKeys,
          onSave: (rowKey, data, row) => {
            //  PatchData(rowKey,data)
            PatchData(rowKey, data);
          },
          // 点击删除
          onDelete: (rowKey) => {
            // setTableListDataSource(tableListDataSource.filter((item) => item.id !== rowKey));
            DeleteData(rowKey)
            // message.success('删除成功!');
            // console.log(rowKey)
          },
          onCancel: () => {
            message.info('已取消编辑');
          },
        }}
        dateFormatter="string"
        toolbar={{
          title: '活动申请表',
          tooltip: '欢迎您来到活动申请模块~',
        }}
        
        toolBarRender={() => [
          <Button key="danger" danger onClick={() => { message.error("功能暂未开通~") }}>
            批量导出
          </Button>,
          <Button key="show" onClick={() => { message.error("功能暂未开通~") }}>批量导入</Button>,
          <><Button type="primary" key="primary" onClick={showModal}>
            新建任务
          </Button>
            {/* <Modal title="新建任务" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}> */}
            <Modal title="创建活动表单" open={isModalOpen} onCancel={handleCancel} footer={null}>
              <Form
                {...layout}
                form={form}
                name="control-hooks"
                onFinish={onFinish}
                style={{ maxWidth: 600 }}
              >
                <Form.Item name="activityname" label="活动名称" rules={[{ required: true, message: "此为必填信息" }]}>
                  <Input />
                </Form.Item>
                <Form.Item label="活动描述" name="activitydescribe" rules={[{ required: true, message: 'Please input!' }]}>
                  <Input.TextArea />
                </Form.Item>
                <Form.Item name="activitycount" label="活动人数" rules={[{ required: true, message: "此为必填信息" }]}>
                  <Input />
                </Form.Item>
                <Form.Item name="activityposstion" label="活动地点" rules={[{ required: true, message: "此为必填信息" }]}>
                  <Input />
                </Form.Item>

                <Form.Item label="活动时间" name="activitydate" rules={[{ required: true, message: 'Please input!' }]}>
                  <RangePicker />
                </Form.Item>
                <Form.Item name="activitystatus" label="活动状态" rules={[{ required: true }]}>
                  <Select
                    placeholder="请选择状态~"
                    onChange={onGenderChange}
                    allowClear
                  >
                    <Option value="0">草稿</Option>
                    <Option value="1">提交</Option>
                    {/* <Option value="2">同意</Option>
                    <Option value="3">拒绝</Option> */}
                  </Select>
                </Form.Item>

                {/* <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
                >
                  {({ getFieldValue }) =>
                    getFieldValue('gender') === 'other' ? (
                      <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]}>
                        <Input />
                      </Form.Item>
                    ) : null
                  }
                </Form.Item> */}

                <Form.Item {...tailLayout}>
                  <Space>
                    <Button type="primary" htmlType="submit">
                      提交信息
                    </Button>
                    <Button htmlType="button" onClick={onReset}>
                      重置信息
                    </Button>
                    {/* <Button type="link" htmlType="button" onClick={onFill}>
                      Fill form
                    </Button> */}
                  </Space>
                </Form.Item>
              </Form>
            </Modal></>,
          // <Dropdown
          //   key="menu"
          //   menu={{
          //     items: [
          //       {
          //         label: '1st item',
          //         key: '1',
          //       },
          //       {
          //         label: '2nd item',
          //         key: '2',
          //       },
          //       {
          //         label: '3rd item',
          //         key: '3',
          //       },
          //     ],
          //   }}
          // >
          //   <Button>
          //     <EllipsisOutlined />
          //   </Button>
          // </Dropdown>,
        ]}
      />
    </PageContainer>
  );
};